package com.android.plc.ui.control;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;

import com.android.plc.CONST;
import com.android.plc.R;
import com.android.plc.classholder.Profile;
import com.android.plc.provider.PLC.ProfileDetails;

public class ProfileControl extends BaseControl implements OnClickListener
{
	public ImageButton mOnBtn;

	public ProfileControl(Context context, ViewGroup view, int res_id)
	{
		super(context, view, res_id);
	}

	public ProfileControl(Context context, ViewGroup view)
	{
		super(context, view, R.layout.control_profile);
	}

	@Override
	public void initView(ViewGroup view)
	{
		mOnBtn = (ImageButton) view.findViewById(R.id.btn_on);

		mOnBtn.setOnClickListener(this);
	}

	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.btn_on:
			dialog();
			break;
		default:
			break;
		}
	}

	protected void dialog()
	{
		Profile profile = mControlManager.getProfile();
		String format = mContext.getString(R.string.tips_profile);
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setMessage(String.format(format, profile.name == null ? "" : profile.name));
		builder.setTitle(R.string.tips);
		builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int which)
			{
				Thread senderThread = new Thread(sender);
				senderThread.start();
				dialog.dismiss();
				mControlManager.swtichControl();
			}
		});
		builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	private Runnable sender = new Runnable()
	{
		public void run()
		{
			Profile profile = mControlManager.getProfile();
			ContentResolver resolver = mContext.getContentResolver();
			Cursor cursor = resolver.query(ProfileDetails.CONTENT_URI, null, ProfileDetails.PROFILE_ID + " = "
					+ profile._id, null, null);

			while (cursor.moveToNext())
			{
				int home_unit_idx = cursor.getColumnIndex(ProfileDetails.ROOM_UNIT);
				int command_idx = cursor.getColumnIndex(ProfileDetails.COMMAND);
				int command = cursor.getInt(command_idx);
				int homeuint = cursor.getInt(home_unit_idx);
				sendUnitCommand(homeuint, command, CONST.DEF_DATA, 0, cursor.getPosition() * CONST.SLEEP_TIME);
			}
			cursor.close();
		}
	};

	@Override
	public void onReceive(int command, int data1, int data2)
	{

		// mControlManager.getProfile()
	}

}
